package com.ktjy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktjy.dto.LoginUser;
import com.ktjy.mapper.SysMenuMapper;
import com.ktjy.mapper.SysUserMapper;
import com.ktjy.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询数据库
        QueryWrapper qw=new QueryWrapper();
        qw.eq("user_name",username);
        SysUser sysUser = sysUserMapper.selectOne(qw);

        if(sysUser==null){
            throw new RuntimeException("用户不存在");
        }
        //查询当前用户所拥有的权限标识
        List<String> perms = sysMenuMapper.getPermsByUserId(sysUser.getUserId());
        Set<String> set=new HashSet<>();
        for (String perm : perms) {
            if(perm!=null&& !"".equals(perm)){
                set.add(perm);
            }
        }
        if("admin".equals(username)){//如果是超级管理员admin
            set.add("*:*:*");
        }
        return new LoginUser(sysUser.getUserId(),sysUser.getUserName(),sysUser.getPassword(),sysUser.getRealName(),set);
    }
}
